# Clase generica implementada como base para el motor de datos utilizado
# Autor: Fernando Mancia


import sys, os
import cPickle as pickle

from model.Alumnos import Alumnos
from model.Alumnos_Lecciones import Alumnos_Lecciones

from sugar.activity import activity
from sugar.datastore import datastore

class GenericDao:

    def get_entidad(self, clave, valor):
        #print "\n----------- INI GET_"+clave+"="+valor+"__---------\n"

     	'''ds_objects, num_objects = datastore.find({clave:valor, 'title_set_by_user': 1})
        print "\n " + clave + " = "+ valor 
	print "\n Cantidad = "+ str(num_objects)
	encontrado = False
	c = 0
	retornar = ""
        for datOb in ds_objects:
		valorCl = datOb.metadata[clave]
		if(valorCl == valor):
			c = c+1
			encontrado = True'''
	try:
        	file_path = os.path.join(activity.get_activity_root(), 'data', valor)
		filehandler = open(file_path, 'r')
		retornar = pickle.load(filehandler)
		filehandler.close()
	except:
		retornar = None
	
	'''    	datOb.destroy()

	if(c == 0):
		retornar = None
	print "\n Se encontro " + str(c) + "."
        print "\n---------- FIN GET_"+clave+"="+valor+"__-------------\n"'''
	return retornar


    def borrar(self, clave, valor):
        print "\n--------- INI Guardando_"+clave+"="+valor+"__--------\n"
        filename = valor
	try:
        	file_path = os.path.join(activity.get_activity_root(), 'data', filename)
		os.remove(file_path)
	except:
		print "No existia ", valor
        print "\n-------- FIN Borrado_"+clave+"="+valor+"__--------\n"

	


    def guardarObjeto(self, clave, valor, objeto):
        #print "\n--------- INI Guardando_"+clave+"="+valor+"__--------\n"
        filename = valor

        file_path = os.path.join(activity.get_activity_root(), 'data', filename)
        f = open(file_path, 'w')
        try:
            pickle.dump(objeto, f)
	    #print "\n  En path "+ file_path + "."
	except:
	    print "\n  Error al guadar ["+clave+"="+valor+"] en path "+ file_path + ". " + sys.exc_info()[0]
        finally:
            f.close()

        #print "\n-------- FIN Guardando_"+clave+"="+valor+"__--------\n"


